package com.gitee.cui.netty.protocol;

import com.gitee.cui.netty.NettyDemoConfig;
import com.gitee.cui.util.Logger;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringEncoder;

/**
 * Json编码客户端，将JsonMsg序列化为Json字符串，再将Json字符串编码成ByteBuf发送到服务端
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/25 13:28
 **/
public class JsonClient {

    private String serverIp;

    private int serverPort;

    private static final Bootstrap BOOTSTRAP = new Bootstrap();

    private static final String content = "测试字符串";

    public JsonClient(String serverIp, int serverPort) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public static void main(String[] args) {
        new JsonClient(NettyDemoConfig.SOCKET_SERVER_IP, NettyDemoConfig.SOCKET_SERVER_PORT).runClient();
    }

    /**
     * 启动客户端程序
     */
    private void runClient() {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            BOOTSTRAP.group(worker);
            BOOTSTRAP.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            BOOTSTRAP.channel(NioSocketChannel.class);
            BOOTSTRAP.remoteAddress(serverIp, serverPort);
            BOOTSTRAP.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LengthFieldPrepender(4));
                    ch.pipeline().addLast(new StringEncoder());
                }
            });

            ChannelFuture future = BOOTSTRAP.connect();
            future.addListener(listener -> {
                if (listener.isSuccess()) {
                    Logger.info("客户端连接成功！");
                } else {
                    Logger.info("客户端连接失败！");
                }
            });
            future.sync();

            // 发送Json字符串对象
            Channel channel = future.channel();
            for (int i = 0; i < 1000; i++) {
                JsonMsg jsonMsg = build(i, i + "->" + content);
                String json = jsonMsg.convertToString();
                channel.write(json);
                Logger.info("发送报文信息：" + json);
            }
            channel.flush();

            ChannelFuture closeFuture = channel.closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }

    /**
     * 构建Json对象信息
     * @param i
     * @param s
     * @return
     */
    private JsonMsg build(int i, String s) {
        JsonMsg jsonMsg = new JsonMsg();
        jsonMsg.setId(i);
        jsonMsg.setContent(s);
        return jsonMsg;
    }
}
